import dataHandle from './encrypt'

/**
 * @param {} config 请求设置
 */
const encryptData = (config) => {
	const data = config.data || config.data * 1 === 0 ? config.data : {}
	const needEncryptData = window.JSON.stringify(data)
	const encryptData = dataHandle.encrypt(
		needEncryptData,
		process.env.VUE_APP_KEY
	)
	const nonce = dataHandle.createNonce()
	const timestamp = dataHandle.createTimestamp()
	const sign = dataHandle.createSign(
		encryptData,
		nonce,
		timestamp,
		process.env.VUE_APP_KEY
	)
	config.headers['ob-nonce'] = nonce
	config.headers['ob-timestamp'] = timestamp
	config.headers['ob-sign'] = sign
	config.data = encryptData
	return config
}

// 数据解密
const decryptData = (data) => {
	try {
		const res = dataHandle.decrypt(data, process.env.VUE_APP_KEY)
		return res || ''
	} catch (error) {
		console.log(error)
	}
}

// 数据加密
const encryptData2 = (data) => {
	data = data || data * 1 === 0 ? data : {}
	return dataHandle.encrypt(JSON.stringify(data), process.env.VUE_APP_KEY)
}

export default { encryptData, decryptData, encryptData2 }
